/*
 * StoreDAO.java
 *
 * Created on March 5, 2007, 4:20 PM
 */

package edu.byu.isys413.jjenkins.data;
 
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

/**
 * This class contains methods to create, read, update and delete the
 * store Object. It also contains methods to read an object by
 * serveral different criteria. All interaction between the object
 * and the database is done through this class.
 *
 * @author      Jeff Jenkins
 * @version     1.0
 *
 */
public class StoreDAO {
    
    /**
     * singleton instance
     */
    private static StoreDAO instance = null;
    
    /** Creates a new instance of StoreDAO */
    private StoreDAO() {
    }
    
        /** This method implements the singleton pattern. It insures that only
         * on instance of StoreDAO exists
         *
         * @return StoreDAO instance */
    
    public static synchronized StoreDAO getInstance() {
        if (instance == null) {
            instance = new StoreDAO();
        }
        return instance;
    }
    
         /** This method creates a new StoreBO with a unique QUID, puts the interest
          * in cache, and then returns it to the calling method.
          *
          * @return StoreBO
          * @throws DataException
          */
    
    public StoreBO create() throws DataException {
        try {
            
            String id = GUID.generate();
            StoreBO object = new StoreBO();
            object.setId(id);
            Cache.getInstance().put(object.getId(), object);
            return object;
        } catch (Exception e) {
            throw new DataException("Could not create GUID", e);
        }
        
    }
    
    
    /**
     * This is the public read statement.  It loads an existing record
     * from the database.
     * @return StoreBO
     * @param id id of store
     * @throws DataException 
     */
    public synchronized StoreBO read(String id) throws DataException {
        
        // Checks to see if the item is in cache
        Cache cache = Cache.getInstance();
        StoreBO object = (StoreBO)cache.get(id);
        try {
            
            // Gets connection
            ConnectionPool connPool = ConnectionPool.getInstance();
            Connection conn = connPool.get();
            
            // If the item is not in cache a connection is checked out and
            // The item is read from the database.
            if(object == null){
                try {
                    //reads in object
                    object = read(id, conn);
                    
                }catch (SQLException e) {
                    conn.rollback();
                    throw new DataException("Could not retrieve record for id=" + id, e);
                }
            }
            
            // connection committs and is returned.
            conn.commit();
            connPool.release(conn);
            
            
            
        } catch (SQLException e) {
            throw new DataException("Could not retrieve record for id=" + id, e);
        } catch (DataException e) {
            throw new DataException("Could not retrieve record for id=" + id, e);
        } catch (ConnectionPoolException e) {
            throw new DataException("Could not retrieve record for id=" + id, e);
        }
        
        // Return object
        return object;
    }
    
    /**
     *  This is a package method that is called by the public read (above) or
     *  by another DAO.  Either way we already have a connection to the database
     *  to use.  The user (controller) code never calls this one directly, since
     *  it can't know about Connection objects or SQLExceptions.
     * @return StoreBO
     * @param id id of store
     * @param conn connection to the database
     * @throws java.sql.SQLException 
     * @throws edu.byu.isys413.jjenkins.data.DataException 
     */
    synchronized StoreBO read(String id, Connection conn) throws SQLException, DataException {
        
        
        // Checks to see if the item is in cache
        Cache cache = Cache.getInstance();
        StoreBO object = (StoreBO)cache.get(id);
        
        // Quieries that database
        if(object == null){
            
            PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM store WHERE store_id = ?");
            pstmt.setString(1, id);
            pstmt.execute();
            ResultSet rs = pstmt.getResultSet();
            
            if (rs.next()) {
                object = new StoreBO();
                object.setId(rs.getString("store_id"));
                object.setLocation(rs.getString("location"));
                if(rs.getString("manager") != null){
                object.setManager(EmployeeDAO.getInstance().read(rs.getString("manager"), conn));
                }
                object.setAddress(rs.getString("address"));
                object.setPhone(rs.getString("phone"));
                
                
                
                // Sets already in database
                object.setObjectAlreadyInDB(true);
                
                // adds to cache
                cache.put(object.getId(), object);
                
            }else{
                throw new DataException("Object was not found in the database.");
            }
        }
        
        
        // returns object
        return object;
    }
    
    /**
     * This is the public save method.  It is what is called when
     * the user (controller) code wants to save or update an object
     * into the database.
     * @param object StoreBO
     * @throws edu.byu.isys413.jjenkins.data.DataException 
     */
    public synchronized void save(StoreBO object) throws DataException {
        try {
            
            
            // retrieve a database connection from the pool
            ConnectionPool connPool = ConnectionPool.getInstance();
            
            Connection conn = connPool.get();
            
            
            try {
                
                // Saves Interest
                save(object, conn);
                
            }catch (SQLException e) {
                conn.rollback();
                throw new DataException("Could not save record for" + object.getId(), e);
            }
            
            // connection committs and is returned.
            conn.commit();
            connPool.release(conn);
            
            // touch the cache for the object
            Cache.getInstance().touch(object.getId());
            
            
            
        } catch (DataException e) {
            throw new DataException("Could not save record for" + object.getId(), e);
        } catch (ConnectionPoolException e) {
            throw new DataException("Could not save record for" + object.getId(), e);
        } catch (SQLException e) {
            throw new DataException("Could not save record for" + object.getId(), e);
        }
        
        
    }
    
    /**
     *  This is a package method that is called by the public save (above) or
     *  by another DAO.  Either way we already have a connection to the database
     *  to use.  The user (controller) code never calls this one directly, since
     *  it can't know about Connection objects or SQLExceptions.
     * 
     *  By having other DAOs call this save method (rather than update or
     *  insert below, each DAO in a chained save (like the CustomerDAO calling
     *  MembershipDAO calling InterestDAO save chain) can independently decide
     *  whether to udpate or insert the BO it's saving.  That's why I made
     *  update and insert private rather than package level -- if you call
     *  them directly from another DAO, this DAO can't decide whether it's
     *  object needs to be inserted or updated.
     * @param object StoreBO
     * @param conn connection to the database
     * @throws java.sql.SQLException 
     * @throws edu.byu.isys413.jjenkins.data.DataException 
     */
    synchronized void save(StoreBO object, Connection conn) throws SQLException, DataException {
        
        // check the dirty flag in the object.  if it is dirty,
        // run update or insert
        if (object.isDirty()) {
            if (object.isObjectAlreadyInDB()) {
                update(object, conn);
            }else{
                insert(object, conn);
            }
            object.setDirty(false);
        }
        
        
        
    }
    
    /**
     * This method is really a part of save(bo, conn) above.  It could be
     * embedded directly in it, but I've separated it into it's own method
     * to isolate the SQL udpate statement and make it more readable.  But
     * logically, it's really just a part of save.
     * @param object StroreBO
     * @param conn connection to the database
     * @throws java.sql.SQLException 
     * @throws edu.byu.isys413.jjenkins.data.DataException 
     */
    private synchronized void update(StoreBO object, Connection conn) throws SQLException, DataException {
        
        PreparedStatement pstmt = conn.prepareStatement("UPDATE store SET store_id = ?, location = ?, manager = ?, address = ?, phone = ? WHERE store_id = ?");
        pstmt.setString(1, object.getId());
        pstmt.setString(2, object.getLocation());
        pstmt.setString(3, object.getManager().getId());
        pstmt.setString(4, object.getAddress());
        pstmt.setString(5, object.getPhone());
        pstmt.setString(6, object.getId());
        
        pstmt.execute();
        
    }
    
    /**
     * This method is really a part of save(bo, conn) above.  It could be
     * embedded directly in it, but I've separated it into it's own method
     * to isolate the SQL insert statement and make it more readable.  But
     * logically, it's really just a part of save.
     * @param object StoreBO
     * @param conn connection to the database
     * @throws java.sql.SQLException 
     * @throws edu.byu.isys413.jjenkins.data.DataException 
     */
    private synchronized void insert(StoreBO object, Connection conn) throws SQLException, DataException {
        
        // Creates prepared statemetn
        PreparedStatement pstmt = conn.prepareStatement("INSERT INTO store VALUES(?, ?, ?, ?, ?)");
        pstmt.setString(1, object.getId());
        pstmt.setString(2, object.getLocation());
        pstmt.setString(3, object.getManager().getId());
        pstmt.setString(4, object.getAddress());
        pstmt.setString(5, object.getPhone());
        
        //Executes prepated statement
        pstmt.execute();
        
        //Sets already in database true
        object.setObjectAlreadyInDB(true);
        
    }
    
    
    /**
     * We intentionally do not allow a StoreBO object to be deleted because
     * it could mess up relationships in the database. Obmitting the delete
     * also prevents fraud.
     * @param StoreBO 
     * @throws edu.byu.isys413.jjenkins.data.DataException 
     */
    
    public synchronized void delete(CustomerBO customer)throws DataException{
    /* We intentionally do not allow a StoreBO object to be deleted because
     * it could mess up relationships in the database. Obmitting the delete
     * also prevents fraud. */
        throw new DataException("You can not delete a StoreBO");
    }
    
    /**
     * This method reads all the available stores from the database
     * @throws java.sql.SQLException 
     * @throws edu.byu.isys413.jjenkins.data.DataException 
     * @return list of stores
     */
    public synchronized List readAll() throws SQLException, DataException {
        
        List list = new LinkedList();
        
        try {
            
            // Gets connection
            ConnectionPool connPool = ConnectionPool.getInstance();
            Connection conn = connPool.get();
            
            // prepares statemnt
            
            PreparedStatement pstmt = conn.prepareStatement("SELECT store_id FROM store");
            pstmt.execute();
            ResultSet rs = pstmt.getResultSet();
            
            
            while(rs.next()){
                String line_id = rs.getString("store_id");
                list.add(read(line_id, conn));
            }
            
            // connection committs and is returned.
            conn.commit();
            connPool.release(conn);
            
            
            
        } catch (SQLException e) {
            throw new DataException("Could not retrieve record", e);
        } catch (DataException e) {
            throw new DataException("Could not retrieve record", e);
        } catch (ConnectionPoolException e) {
            throw new DataException("Could not retrieve record", e);
        }
        
        
        
        return list;
    }
    
    /**
     * Thie method gets all of the products in a store
     * @param id store id
     * @return 
     */
    public List getAllProductsByStore(String id) {
        List list = new LinkedList();
        Connection conn = null;//this might cause problems later...
        try {
            
            conn = ConnectionPool.getInstance().get();
            
            list = getAllProductsByStore(id, conn);
            
        } catch (ConnectionPoolException ex) {
            ex.printStackTrace();
        }catch (DataException dex){
            dex.printStackTrace();
        }catch (SQLException ex) {
            try {
                conn.rollback();
                
            } catch (SQLException exe) {
                System.out.println("really big error, cant rollback in StoreDAO!");
                ex.printStackTrace();
            }
            ex.printStackTrace();
        }
        
        
        return list;
    }
    
    /**
     * this method gets all the products by the store and takes 
     * a connection
     * @param id id of store
     * @param conn connection to database
     * @throws java.sql.SQLException 
     * @throws edu.byu.isys413.jjenkins.data.DataException 
     * @return 
     */
    public List getAllProductsByStore(String id, Connection conn) throws SQLException, DataException {
        List list = new LinkedList();
        
        PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM store_product WHERE store_id = ?");
        pstmt.setString(1, id);
        pstmt.execute();
        
        ResultSet rs = pstmt.getResultSet();
        while(rs.next()){
            StoreProductBO prod = StoreProductDAO.getInstance().create();
            prod.setQtyOnHand(rs.getInt("qty_on_hand"));
            prod.setQtyOnOrder(rs.getInt("qtu_on_order"));
            prod.setQtyToOrder(rs.getInt("qtu_to_order"));
            prod.setReorderPoint(rs.getInt("reorder_point"));
            prod.setId(rs.getString("product_id"));//should i set the id as this, or as the combination of the 2 FK's??
            
            list.add(prod);
            
        }
        
        
        
        return list;
    }
    
}
